import React, { useState, useRef } from 'react';
import { Layout, Row, Col, Card, Button, message, Modal, Form, Input, InputNumber } from 'antd';
import { ArrowLeftOutlined, DownloadOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import html2canvas from 'html2canvas';
import { WineMenuCanvas } from './components/WineMenuCanvas';
import { ConfigPanel } from './components/ConfigPanel';
import { ProductSelector } from './components/ProductSelector';
import type { WineMenuConfig, WineItem } from './types';
import './WineMenuGeneratorPage.css';

const { Content } = Layout;

const defaultConfig: WineMenuConfig = {
    layout: {
        rows: 3,
        cols: 5,
        width: 1920,
        height: 1080,
        padding: 20,
        gap: 24,
        aspectRatio: '16/9',
        containerPadding: 40
    },
    border: {
        width: 1,
        color: '#EEEEEE',
        style: 'solid'
    },
    item: {
        image: {
            width: 80,
            height: 80,
            borderRadius: 50,
            marginBottom: 0,
            fit: 'cover',
            position: 'left'
        },
        backgroundColor: '#FFFFFF',
        borderRadius: 12,
        padding: 20,
        hoverEffect: {
            enabled: true,
            transform: true,
            shadow: true,
            scale: 1.02
        }
    },
    fonts: {
        brewery: {
            size: 22,
            color: '#000',
            weight: 'bold',
            family: 'Arial',
            show: true
        },
        name: {
            size: 40,
            color: '#000',
            weight: 'bold',
            family: 'Arial'
        },
        price: {
            size: 56,
            color: '#000',
            weight: 'bold',
            family: 'Arial',
            dividerShow: true,
            dividerColor: '#EEEEEE',
            dividerWidth: 1,
            dividerStyle: 'solid',
            secondPriceGap: 4
        },
        category: {
            size: 18,
            color: '#000',
            weight: 'bold',
            family: 'Arial'
        },
        abv: {
            size: 18,
            color: '#000',
            weight: 'bold',
            family: 'Arial'
        }
    },
    background: {
        color: '#F5F5F5',
        image: null
    }
};

export const WineMenuGeneratorPage: React.FC = () => {
    const navigate = useNavigate();
    const canvasRef = useRef<HTMLDivElement>(null);
    const [config, setConfig] = useState<WineMenuConfig>(defaultConfig);
    const [wineItems, setWineItems] = useState<WineItem[]>([]);
    const [activeTab, setActiveTab] = useState<'config' | 'products'>('config');
    const [editingItem, setEditingItem] = useState<WineItem | null>(null);
    const [form] = Form.useForm();

    const handleConfigChange = (newConfig: Partial<WineMenuConfig>) => {
        setConfig((prev: WineMenuConfig) => ({ ...prev, ...newConfig }));
    };

    const handleProductsImport = (products: WineItem[]) => {
        const newItems = products.filter(newItem =>
            !wineItems.some(existingItem => existingItem.id === newItem.id)
        );
        setWineItems(prev => [...prev, ...newItems]);
        message.success(`成功添加 ${newItems.length} 个商品`);
        setActiveTab('config');
    };

    const handleItemEdit = (item: WineItem) => {
        form.setFieldsValue(item);
        setEditingItem(item);
    };

    const handleEditSave = (values: WineItem) => {
        if (editingItem) {
            setWineItems(prev => prev.map(item =>
                item.id === editingItem.id ? { ...item, ...values } : item
            ));
            setEditingItem(null);
            form.resetFields();
        }
    };

    const handleEditCancel = () => {
        setEditingItem(null);
        form.resetFields();
    };

    const handleItemDelete = (item: WineItem) => {
        Modal.confirm({
            title: '确认删除',
            content: `确定要删除 ${item.name} 吗？`,
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                setWineItems(prev => prev.filter(i => i.id !== item.id));
                message.success('删除成功');
            }
        });
    };

    const handleExportImage = async () => {
        if (!canvasRef.current) {
            message.error('无法获取画布元素');
            return;
        }

        try {
            const canvas = await html2canvas(canvasRef.current, {
                background: config.background.color,
                width: config.layout.width,
                height: config.layout.height,
                logging: false,
                useCORS: true,
                allowTaint: true,
            });

            // 创建下载链接
            const link = document.createElement('a');
            link.download = `酒单_${new Date().getTime()}.png`;
            link.href = canvas.toDataURL();
            link.click();

            message.success('酒单图片已导出');
        } catch (error) {
            console.error('导出失败:', error);
            message.error('导出失败，请重试');
        }
    };

    return (
        <Layout className="wine-menu-generator-layout">
            <Content className="wine-menu-generator-content">
                <div className="wine-menu-generator-container">
                    {/* 头部 */}
                    <div className="generator-header">
                        <Button
                            icon={<ArrowLeftOutlined />}
                            onClick={() => navigate('/lab')}
                            className="back-button"
                        >
                            返回实验室
                        </Button>
                        <h1 className="generator-title">酒单生成器</h1>
                        <Button
                            type="primary"
                            icon={<DownloadOutlined />}
                            onClick={handleExportImage}
                            className="export-button"
                        >
                            导出图片
                        </Button>
                    </div>

                    {/* 主要内容区域 */}
                    <Row gutter={24} className="generator-main">
                        {/* 左侧配置面板 */}
                        <Col xs={24} lg={8} className="config-section">
                            <Card className="config-card">
                                <div className="config-tabs">
                                    <Button
                                        type={activeTab === 'config' ? 'primary' : 'default'}
                                        onClick={() => setActiveTab('config')}
                                        className="config-tab"
                                    >
                                        样式配置
                                    </Button>
                                    <Button
                                        type={activeTab === 'products' ? 'primary' : 'default'}
                                        onClick={() => setActiveTab('products')}
                                        className="config-tab"
                                    >
                                        商品选择
                                    </Button>
                                </div>

                                <div className="config-content">
                                    {activeTab === 'config' ? (
                                        <ConfigPanel
                                            config={config}
                                            onChange={handleConfigChange}
                                        />
                                    ) : (
                                        <ProductSelector
                                            onImport={handleProductsImport}
                                            selectedItems={wineItems}
                                        />
                                    )}
                                </div>
                            </Card>
                        </Col>

                        {/* 右侧预览区域 */}
                        <Col xs={24} lg={16} className="preview-section">
                            <Card className="preview-card">
                                <div className="preview-header">
                                    <h3>预览效果</h3>
                                    <div className="preview-info">
                                        {config.layout.cols} × {config.layout.rows} 布局 |
                                        <span style={{
                                            marginLeft: '4px'
                                        }}>
                                            {wineItems.length} 个商品
                                        </span>
                                    </div>
                                </div>
                                <div className="preview-container">
                                    <WineMenuCanvas
                                        ref={canvasRef}
                                        config={config}
                                        wineItems={wineItems}
                                        onItemEdit={handleItemEdit}
                                        onItemDelete={handleItemDelete}
                                    />
                                </div>
                            </Card>
                        </Col>
                    </Row>
                </div>
            </Content>

            {/* 编辑弹窗 */}
            <Modal
                title="编辑酒款信息"
                open={!!editingItem}
                onCancel={handleEditCancel}
                footer={null}
                destroyOnClose
            >
                {editingItem && (
                    <Form
                        form={form}
                        initialValues={editingItem}
                        onFinish={handleEditSave}
                        layout="vertical"
                        preserve={false}
                    >
                        <Form.Item label="名称" name="name" rules={[{ required: true, message: '请输入名称' }]}>
                            <Input />
                        </Form.Item>
                        <Form.Item label="酒厂" name="brewery" rules={[{ required: true, message: '请输入酒厂' }]}>
                            <Input />
                        </Form.Item>
                        <Form.Item label="价格" name="price" rules={[{ required: true, message: '请输入价格' }]}>
                            <InputNumber min={0} style={{ width: '100%' }} />
                        </Form.Item>
                        <Form.Item label="第二价格" name="secondPrice">
                            <InputNumber min={0} style={{ width: '100%' }} />
                        </Form.Item>
                        <Form.Item label="类型" name="category">
                            <Input />
                        </Form.Item>
                        <Form.Item label="酒精度" name="abv">
                            <Input />
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit" block>
                                保存
                            </Button>
                        </Form.Item>
                    </Form>
                )}
            </Modal>
        </Layout>
    );
};

export default WineMenuGeneratorPage; 